package com.zzusedating.androidapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.zzusedating.androidapp.adapters.FragAdapterProfile;
import com.zzusedating.androidapp.customlayout.TitleBarLayout;
import com.zzusedating.androidapp.fragments.ProfileFragment;
import com.zzusedating.androidapp.tools.BasicCallback;
import com.zzusedating.androidapp.tools.ConstantsTools;
import com.zzusedating.androidapp.tools.MyApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

public class ProfileActivity extends BaseActivity {
    private static final String TAG = "ProfileActivity";
    private static final Integer MODIFY_TAG = 0;
    private static final Integer FINISH_TAG = 1;
    private boolean TO_MODIFY = false;

    private static final int GET_PROFILE_SUCCESS_I = 130;
    private static final int GET_MATE_INTENT_SUCCESS_I = 140;
    private static final int USER_NOT_LOGIN_I = 131;
    private static final int USER_NOT_FOUND_I = 132;

    private static final String USER_NOT_LOGIN_ = "用户未登录";
    private static final String USER_NOT_FOUND_ = "用户不存在";

    private Callback detailCallback;
    private Callback intentCallback;
    private Handler handler;

    private View.OnClickListener modifyListener;

    private TitleBarLayout titleBarLayout;
    private ViewPager pager;
    private FragAdapterProfile adapter;
    private TextView selfDesc;

    private JSONObject detail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_layout);

        initListener();
        selfDesc = findViewById(R.id.Profile_SelfDesc);
        pager = findViewById(R.id.Profile_ViewPager);
        adapter = new FragAdapterProfile(getSupportFragmentManager());
        pager.setAdapter(adapter);
        TabLayout tabLayout = findViewById(R.id.Profile_TabLayout);
        tabLayout.setupWithViewPager(pager);

        titleBarLayout = findViewById(R.id.Profile_Title);
        titleBarLayout.setTag(MODIFY_TAG);
        titleBarLayout.setClickListenerTo(modifyListener, TitleBarLayout.TO_TEXT);

        initCallback();


    }

    public JSONObject getDetail() {
        return detail;
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        detail = MyApplication.getDetailProfile();
        if (detail == null) {
            MyApplication.getClient().newCall(
                    new Request.Builder()
                            .get()
                            .url(ConstantsTools.GET_USER_DETAIL)
                            .build()
            ).enqueue(detailCallback);
            MyApplication.getClient().newCall(
                    new Request.Builder()
                            .get()
                            .url(ConstantsTools.GET_USER_MATE_INTENT)
                            .build()
            ).enqueue(intentCallback);
        }
    }

    @Override
    protected void initListener() {
        modifyListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TO_MODIFY) {
                    titleBarLayout.setRightText(getResources().getString(R.string.finish));
                    TO_MODIFY = true;
                } else {
                    // todo send modified profile
                    try {
                        JSONObject jsonObject = adapter.getProfileFrag().getData();
                        JSONObject favourJson = adapter.getMateIntentFrag().getData();

                        MultipartBody.Builder body = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM);
                        body.addFormDataPart("selfIntro", selfDesc.getText().toString());
                        JSONArray array = jsonObject.names();
                        for (int i = 0; i < array.length(); i++) {
                            String name = array.getString(i);
                            body.addFormDataPart(name, jsonObject.getString(name));
                        }
                        body.addFormDataPart("favour", favourJson.toString());
                        // mate intent
                        MyApplication.getClient().newCall(
                                new Request.Builder()
                                        .url(ConstantsTools.MODIFY_PROFILE)
                                        .post(body.build())
                                        .build()
                        ).enqueue(new BasicCallback(handler) {
                            @Override
                            public void onResponse(Call call, @NonNull Response response) {
                                getStatus(response);
                                handler.sendMessage(ConstantsTools.createMessage(getCode()));
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    @Override
    protected void initCallback() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case USER_NOT_FOUND_I:
                        MyApplication.Toast(USER_NOT_FOUND_);
                        break;
                    case USER_NOT_LOGIN_I:
                        MyApplication.Toast(USER_NOT_LOGIN_);
                        break;
                    case ConstantsTools.NETWORK_ERROR_I:
                        MyApplication.Toast(ConstantsTools.NETWORK_ERROR_);
                        break;
                    case GET_PROFILE_SUCCESS_I:
                        ProfileFragment fragment = (ProfileFragment) adapter.getItem(0);
                        try {
                            selfDesc.setText(MyApplication.getBasicProfile().getString("selfIntro"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        fragment.setData((JSONObject) msg.obj);
                        break;
                    case GET_MATE_INTENT_SUCCESS_I:
                        break;
                    case -1:
                        MyApplication.Toast("未登录");
                        break;
                    case 2:
                        MyApplication.Toast("参数错误");
                        break;
                    case 0:
                        MyApplication.Toast("未知错误");
                        break;
                    case 1:
                        MyApplication.Toast("修改成功");
                        titleBarLayout.setRightText(getResources().getString(R.string.modify));
                        TO_MODIFY = false;
                        break;
                    default:
                        MyApplication.Toast("网络错误");
                }
                return true;
            }
        });
        detailCallback = new BasicCallback(handler) {
            @Override
            public void onResponse(Call call, @NonNull Response response) {
                JSONObject jsonObject = (JSONObject) getObject(response);
                if (jsonObject != null) {
                    handler.sendMessage(ConstantsTools.createMessage(GET_PROFILE_SUCCESS_I, jsonObject));
                }
            }
        };
        intentCallback = new BasicCallback(handler) {
            @Override
            public void onResponse(Call call, @NonNull Response response) {
                JSONObject jsonObject = (JSONObject) getObject(response);
                if (jsonObject != null) {
                    handler.sendMessage(ConstantsTools.createMessage(GET_MATE_INTENT_SUCCESS_I, jsonObject));
                } else {
                    int code = getCode();
                    switch (code) {
                        case -1:
                            handler.sendMessage(ConstantsTools.createMessage(USER_NOT_LOGIN_I));
                            break;
                        case 5:
                            handler.sendMessage(ConstantsTools.createMessage(USER_NOT_FOUND_I));
                            break;
                        default:
                            handler.sendMessage(ConstantsTools.createMessage());
                    }
                }
            }
        };

    }
}
